﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using TsCore;
using TsWeb.Model;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;

namespace TsWeb.Services
{
    [ServiceContract(Namespace = "")]
    [SilverlightFaultBehavior]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ServiceMatch
    {
        public ServiceMatch()
        {
            System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User;
        }

        [OperationContract]
        //[PrincipalPermission(SecurityAction.Demand, Role = "Administradores")]
        public List<WCFMatch> GetMatchList(WCFSport sport)
        {
            List<WCFMatch> toReturn = new List<WCFMatch>();
            Sport currentSport = TsSystem.Instance.GetSport(sport.Name);

            foreach (Match toParseMatch in TsSystem.Instance.GetMatchesForSport(currentSport))
            {
                if (!(toParseMatch.HomeTeam.IsDummyTeam || toParseMatch.VisitorTeam.IsDummyTeam))
                {
                    toReturn.Add(this.MatchToWCFMatch(toParseMatch));
                }
            }

            return toReturn;
        }

        [OperationContract]
        //[PrincipalPermission(SecurityAction.Demand, Role = "Administrador")]
        public List<WCFSport> GetSportList()
        {
            List<WCFSport> toReturn = new List<WCFSport>();

            foreach (Sport toParseSport in TsSystem.Instance.GetAllSports())
            {
                toReturn.Add(this.SportToWCFSport(toParseSport));
            }

            return toReturn;
        }

        private WCFSport SportToWCFSport(Sport toParse)
        {
            WCFSport parsedWCFSport = new WCFSport();

            parsedWCFSport.Id = toParse.SportId;
            parsedWCFSport.Name = toParse.Name;

            return parsedWCFSport;
        }

        private WCFMatch MatchToWCFMatch(Match toParse)
        {
            WCFMatch parsedWCFMatch = new WCFMatch();

            parsedWCFMatch.Date = toParse.Date;
            parsedWCFMatch.HomeTeam = toParse.HomeTeam.Name;
            parsedWCFMatch.MatchId = toParse.MatchId;

            List<String> media = new List < String >();
            foreach (var item in toParse.MediaList)
            {                
                media.Add(item.Medias);
            }

            parsedWCFMatch.MediaList = media;
            parsedWCFMatch.Name = toParse.Name;
            parsedWCFMatch.VisitorTeam = toParse.VisitorTeam.Name;
            
            return parsedWCFMatch;
        }
    }
    
}
